package com.jlsoft.cordova;

import com.ccb.smartpos.clientauth.AuthHelper;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 建行POS设备，第三方APP授权认证插件
 */
public class AuthCCBPlugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("initAuth")) {
            initAuth(String.valueOf(args.get(0)), callbackContext);
        } else if (action.equals("getAuthInfo")) {
            getAuthInfo(String.valueOf(args.get(0)), callbackContext);
        } else {
            return false;
        }

        return super.execute(action, args, callbackContext);
    }

    /**
     * 授权初始化
     *
     * @param authCode
     * @param callbackContext
     */
    public void initAuth(String authCode, CallbackContext callbackContext) {
        if (authCode == null) {
            callbackContext.error("authCode is null!");
        }
        AuthHelper.init(this.cordova.getContext(), authCode);
        callbackContext.success("auth init is success.");
    }

    /**
     * 获取授权码
     *
     * @param param
     * @param callbackContext
     * @throws JSONException
     */
    public void getAuthInfo(String param, CallbackContext callbackContext) throws JSONException {
        String[] result = AuthHelper.getAuthCode(this.cordova.getContext(), param);

        JSONObject json = new JSONObject();
        json.put("authCode", result[0]);
        json.put("authIndex", result[1]);

        callbackContext.success(json);
    }
}
